<template>
  <div>
    <el-card class="banner-card" v-if="hasAuth('template:list')">
      <div slot="header" class="clearfix">
        <span>首页轮播图</span>
      </div>
      <el-upload
          action="#" :file-list="imageList" :append-to-body="true" ref="imageUpload"
          list-type="picture-card" :auto-upload="false" :on-change="imageChange">
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img class="el-upload-list__item-thumbnail"
               :src="file.url" alt="">
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview"
                  @click="imageCardPreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span class="el-upload-list__item-delete" v-if="hasAuth('template:add')"
                  @click="imageDownload(file)">
              <i class="el-icon-download"></i>
            </span>
            <span class="el-upload-list__item-delete" v-if="hasAuth('template:delete')"
                  @click="imageRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
      </el-upload>
      <el-dialog :visible.sync="showImage" v-if="hasAuth('template:list')">
        <img width="100%" :src="imageUrl" alt="">
      </el-dialog>
    </el-card>
    <el-divider></el-divider>

    <el-form :inline="true" v-if="hasAuth('template:list')">
      <el-form-item>
        <el-button type="primary" @click="editNotice(null)">新增公告</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="notice"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="selectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="首页提示文字"
          show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.data }}</template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="90">
        <template slot-scope="scope">
          <el-button @click="editNotice(scope.row)" type="text" size="small" v-if="hasAuth('template:update')">编辑</el-button>
          <el-button @click="deleteNotice(scope.row)" type="text" size="small" v-if="hasAuth('template:delete')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <admin-footer/>
  </div>
</template>

<script>
import {addBanner, addNotice, deleteBanner, deleteNotice, getAllTemplate, updateNotice} from "@/network/template";
import AdminFooter from "@/components/conment/adminfooter/AdminFooter";
import {hasPermission} from "@/utils/mixin";

export default {
  name: "Template",
  components: {AdminFooter},
  mixins:[hasPermission],
  data(){
    return{
      notice:[],
      imageUrl: '',
      showImage: false,
      imageList:[],
    }
  },
  methods:{
    //文件类型检测
    checkFileOk(file) {
      const isJPG = file.type === 'image/jpeg';
      const isGIF = file.type === 'image/gif';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false
      }
      return (isJPG || isBMP || isGIF || isPNG) && isLt10M;
    },
    async imageChange(file, fileList){
      if (this.checkFileOk(file.raw)) {//文件类型检查通过
        let s = fileList.filter(s=>s.name===file.raw.name)
        if (s.length>1){
          this.$message.error(file.name+" 文件已存在！")
          fileList.pop()
        }else {//上传文件
          let form = new FormData()
          form.append('image', file.raw)//图片数据
          await addBanner(form).then(async res=>{
            console.log(res.data.data)
            this.$message.success('上传成功')
          })
        }
      }else {
        fileList.pop()
      }
    },
    //移除图片
    imageRemove(file) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let s = this.$refs.imageUpload.$data.uploadFiles
        s.splice(s.findIndex(s=>s.name === file.name),1)
        deleteBanner(file.name).then(res=>{
          this.$message.success('删除成功')
        })
      })
    },
    //点击查看图片
    imageCardPreview(file) {
      this.imageUrl = file.url;
      this.showImage = true;
    },
    imageDownload(file) {
      window.open(file.url)
    },
    editNotice(row){
      this.$prompt(row?'修改公告':'请输入通告内容', '公告操作', {
        type:'warning ',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row?row.data:'',
        closeOnClickModal:false,
        roundButton: true,
        inputValidator:function (val){
          if (val == null || val.length===0) {
            return '不能为空';
          }
        },
      }).then(({ value }) => {
        if (row){//修改
          row.data = value
          updateNotice(row).then(res=>{
            this.$message.success('修改成功')
          })
        }else {//添加
          addNotice(value).then(res=>{
            this.notice.push(res.data.data)
            this.$message.success('添加成功')
          })
        }
        this.notice.push()
      }).catch(()=>{})
    },
    deleteNotice(row){
      this.$confirm('删除此通告, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteNotice(row.id).then(res=>{
          this.$message.success('删除成功')
          this.notice.splice(this.notice.findIndex(s=>s===row),1)
        })
      })
    },
    selectionChange(){

    },
    getTemplateList(){
      getAllTemplate().then(res=>{
        res.data.data.forEach(s=>{
          if (s.type==='notice'){
            this.notice.push(s)
          }else if(s.type==='banner'){
            this.imageList.push({
              name: s.id,
              url:s.data
            })
          }
        })
      })
    },
  },
  created() {
    this.getTemplateList()
  }
}
</script>

<style scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }
</style>